import axios, { AxiosResponse } from 'axios';
import { localStorage } from '@/utils/local-storage';
import { STORAGE_TOKEN_KEY, STORAGE_USERID } from '@/store/mutation-type';
import { notification } from 'ant-design-vue'; // 这里是用于设定请求后端时，所用的 Token KEY
import router from '@/router';

// 可以根据自己的需要修改，常见的如 Access-Token，Authorization
// 需要注意的是，请尽量保证使用中横线`-` 来作为分隔符，
// 避免被 nginx 等负载均衡器丢弃了自定义的请求头

export const REQUEST_TOKEN_KEY = 'Authorization'; // 创建 axios 实例
export const REQUEST_USERID = 'userId';

let requestNum = 0;
const logOut = () => {
  localStorage.set(STORAGE_TOKEN_KEY, '');
  localStorage.set(STORAGE_USERID, '');
  notification.error({
    message: '请求错误',
    description: '当前登陆状态已过期，请重新登陆',
  });
  setTimeout(() => {
    router.go(0);
  }, 2000);
};

const request = axios.create({
  // API 请求的默认前缀
  baseURL: process.env.VUE_APP_API_BASE_URL,
  timeout: 6000, // 请求超时时间
}); // 异常拦截处理器

const errorHandler = error => {
  requestNum--;
  if (error.response) {
    const { data = {} } = error.response;
    const description = data.message ? data.message : data.error ? data.error : error.message;
    notification.error({
      message: '请求错误',
      description,
    });
  } else {
    const description =
      error.message === 'timeout of 6000ms exceeded' ? '请求超时，请重试~' : error.message;
    notification.error({
      message: '请求错误',
      description,
    });
  }

  return Promise.reject(error);
}; // 请求拦截器

const requestHandler = config => {
  const savedToken = localStorage.get(STORAGE_TOKEN_KEY); // 如果 token 存在
  const userId = localStorage.get(STORAGE_USERID);
  // 让每个请求携带自定义 token, 请根据实际情况修改

  if (savedToken) {
    config.headers[REQUEST_TOKEN_KEY] = savedToken;
    config.headers[REQUEST_USERID] = userId;
  }

  requestNum++;
  return config;
}; // Add a request interceptor

request.interceptors.request.use(requestHandler, errorHandler); // 响应拦截器

const responseHandler = response => {
  requestNum--;
  const { data } = response;
  if (data.code === 200) {
    return response.data;
  } else if (data.code === 401) {
    if (requestNum !== 0) return;
    logOut();
  } else {
    notification.error({
      message: '请求错误',
      description: data && (data.msg || data.message),
    });
    return Promise.reject(new Error(data && (data.msg || data.message)));
  }
}; // Add a response interceptor

request.interceptors.response.use(responseHandler, errorHandler);
export { AxiosResponse };
export default request;
